package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliyunOSSOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) throws Exception {
        //1.获取文件名
        String fileName = file.getOriginalFilename();
        //2.获取文件后缀
        String substring = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        //3.随机生成文件名并加入后缀
        String replace = UUID.randomUUID().toString().replace("-", "")+substring;
        //4.创建文件对象
        String url = aliyunOSSOperator.upload(file.getBytes(), replace);
        //5.判断文件是否存在
        if (file.isEmpty()){
            return Result.error("文件为空");
        }else {
            //6.上传文件
            return Result.success(url);
        }
    }
}
